/**
 * 
 */
package dk.itu.mobile.util;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

/**
 * @author group 02
 * 
 */
public class CryptoBaws {
	private static byte[] linebreak = {};
	private static Base64 coder = new Base64(16, linebreak, true);

	/**
	 * encode encrypts a String
	 * @param value String for encryption
	 * @param secret 'Key' to encrypt, length must be 16
	 * @return encrypted String
	 * @throws Exception
	 */
	public static String encode(String value, String secret) throws Exception {
		SecretKey key = new SecretKeySpec(secret.getBytes(), "AES");
		
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
		cipher.init(Cipher.ENCRYPT_MODE, key);

		byte[] cipherText = cipher.doFinal(value.getBytes());

		return new String(coder.encode(cipherText));
	}

	/**
	 * decode decrypts a String
	 * @param value String to decrypt
	 * @param secret 'Key' for decryption, length must be 16
	 * @return decrypted String
	 * @throws Exception
	 */
	public static String decode(String value, String secret) throws Exception {
		SecretKey key = new SecretKeySpec(secret.getBytes(), "AES");
		
		byte[] encypted = coder.decode(value.getBytes());

		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
		cipher.init(Cipher.DECRYPT_MODE, key);

		byte[] decrypted = cipher.doFinal(encypted);

		return new String(decrypted);
	}

	public static void main(String[] args) throws Exception {
		String testMessage = "The Super Secret Message ++";
		String testSecret = "very 1337 secret";

		System.out.println("Message: " + testMessage);

		String encryptedMessage = encode(testMessage, testSecret);
		System.out.println("Encrypted Message: " + encryptedMessage);

		String decryptedMessage = decode(encryptedMessage, testSecret);
		System.out.println("Decrypted Message: " + decryptedMessage);
	}
}
